
Product
Announcing Precomputed Reachability Analysis in Socket
Socket’s precomputed reachability slashes false positives by flagging up to 80% of vulnerabilities as irrelevant, with no setup and instant results.
TypeScript-first schema declaration and validation library with static type inference
Zod is a TypeScript-first schema declaration and validation library. It allows developers to create complex schemas for data validation with a simple and intuitive API. Zod schemas are composable and can be used to validate data at the edge of your application, ensuring that you're working with well-structured and type-safe data.
Basic Type Validation
Validates that the input is a string.
{"const schema = zod.string(); try { schema.parse('hello world'); } catch (e) { console.error(e); }"}
Object Schema Validation
Validates that the input is an object with specific properties of certain types.
{"const userSchema = zod.object({ name: zod.string(), age: zod.number(), email: zod.string().email() }); try { userSchema.parse({ name: 'John', age: 30, email: 'john@example.com' }); } catch (e) { console.error(e); }"}
Array Validation
Validates that the input is an array of strings.
{"const stringArraySchema = zod.array(zod.string()); try { stringArraySchema.parse(['apple', 'banana']); } catch (e) { console.error(e); }"}
Complex Nested Validation
Validates nested objects with various property types.
{"const nestedSchema = zod.object({ user: zod.object({ name: zod.string(), contact: zod.object({ email: zod.string().email(), phone: zod.string() }) }) }); try { nestedSchema.parse({ user: { name: 'Jane', contact: { email: 'jane@example.com', phone: '123-456-7890' } } }); } catch (e) { console.error(e); }"}
Custom Validation
Validates that a number is positive using custom validation logic.
{"const positiveNumber = zod.number().positive(); try { positiveNumber.parse(42); } catch (e) { console.error(e); }"}
Error Formatting
Formats validation errors for easier debugging and display.
{"const schema = zod.string(); try { schema.parse(42); } catch (e) { console.error(e.format()); }"}
Joi is a powerful schema description language and data validator for JavaScript. It offers a similar API to Zod but has been around longer and is often considered more mature. Joi provides a wide range of built-in validators and is highly extensible.
Yup is a JavaScript schema builder for value parsing and validation. It defines a schema with an expressive API and can be used with or without TypeScript. Yup is often used in the context of form validation, especially with libraries like Formik.
Ajv is a JSON Schema Validator. It validates data against JSON Schema (draft 06/07/2019) and is known for its performance. Unlike Zod, which is TypeScript-first, Ajv focuses on JSON Schema validation and is often used for validating data structures in RESTful APIs.
Class-validator allows for validation of class instances based on decorators. It is tightly coupled with TypeScript and uses decorators to define validation rules, which can be more familiar to developers used to working with TypeScript classes and decorators.
TypeScript-first schema validation with static type inference
by @colinhacks
Zod is a TypeScript-first validation library. Define a schema and parse some data with it. You'll get back a strongly typed, validated result.
import * as z from "zod";
const User = z.object({
name: z.string(),
});
// some untrusted data...
const input = {
/* stuff */
};
// the parsed result is validated and type safe!
const data = User.parse(input);
// so you can use it with confidence :)
console.log(data.name);
2kb
core bundle (gzipped)npm install zod
Before you can do anything else, you need to define a schema. For the purposes of this guide, we'll use a simple object schema.
import * as z from "zod";
const Player = z.object({
username: z.string(),
xp: z.number(),
});
Given any Zod schema, use .parse
to validate an input. If it's valid, Zod returns a strongly-typed deep clone of the input.
Player.parse({ username: "billie", xp: 100 });
// => returns { username: "billie", xp: 100 }
Note — If your schema uses certain asynchronous APIs like async
refinements or transforms, you'll need to use the .parseAsync()
method instead.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.parseAsync("hello");
// => "hello"
When validation fails, the .parse()
method will throw a ZodError
instance with granular information about the validation issues.
try {
Player.parse({ username: 42, xp: "100" });
} catch (err) {
if (err instanceof z.ZodError) {
err.issues;
/* [
{
expected: 'string',
code: 'invalid_type',
path: [ 'username' ],
message: 'Invalid input: expected string'
},
{
expected: 'number',
code: 'invalid_type',
path: [ 'xp' ],
message: 'Invalid input: expected number'
}
] */
}
}
To avoid a try/catch
block, you can use the .safeParse()
method to get back a plain result object containing either the successfully parsed data or a ZodError
. The result type is a discriminated union, so you can handle both cases conveniently.
const result = Player.safeParse({ username: 42, xp: "100" });
if (!result.success) {
result.error; // ZodError instance
} else {
result.data; // { username: string; xp: number }
}
Note — If your schema uses certain asynchronous APIs like async
refinements or transforms, you'll need to use the .safeParseAsync()
method instead.
const schema = z.string().refine(async (val) => val.length <= 8);
await schema.safeParseAsync("hello");
// => { success: true; data: "hello" }
Zod infers a static type from your schema definitions. You can extract this type with the z.infer<>
utility and use it however you like.
const Player = z.object({
username: z.string(),
xp: z.number(),
});
// extract the inferred type
type Player = z.infer<typeof Player>;
// use it in your code
const player: Player = { username: "billie", xp: 100 };
In some cases, the input & output types of a schema can diverge. For instance, the .transform()
API can convert the input from one type to another. In these cases, you can extract the input and output types independently:
const mySchema = z.string().transform((val) => val.length);
type MySchemaIn = z.input<typeof mySchema>;
// => string
type MySchemaOut = z.output<typeof mySchema>; // equivalent to z.infer<typeof mySchema>
// number
FAQs
TypeScript-first schema declaration and validation library with static type inference
The npm package zod receives a total of 32,886,433 weekly downloads. As such, zod popularity was classified as popular.
We found that zod demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 0 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket’s precomputed reachability slashes false positives by flagging up to 80% of vulnerabilities as irrelevant, with no setup and instant results.
Product
Socket is launching experimental protection for Chrome extensions, scanning for malware and risky permissions to prevent silent supply chain attacks.
Product
Add secure dependency scanning to Claude Desktop with Socket MCP, a one-click extension that keeps your coding conversations safe from malicious packages.